#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <arpa/inet.h>
#include "cJSON.h"
#include "../lvgl/lvgl.h"
#include "../UI/ui.h"

// 关键：手动声明字体变量
extern const lv_font_t ui_font_Font30;

// 静态UI元素指针
static lv_obj_t *placevalue = NULL;
static lv_obj_t *weathervalue = NULL;
static lv_obj_t *Tempvalue = NULL;
static lv_obj_t *windvalue = NULL;
static lv_obj_t *Humidityvalue = NULL;

// 调试日志宏 - 已完全禁用
#define WEATHER_DEBUG 0
#ifdef WEATHER_DEBUG
#define LOG_DEBUG(...) printf("[WEATHER_DEBUG] " __VA_ARGS__)
#else
#define LOG_DEBUG(...) do {} while(0)  // 使用空循环确保语法正确但无输出
#endif

// 定时器指针
static lv_timer_t *weather_timer = NULL;

// 定时器回调函数
static void weather_timer_callback(lv_timer_t *timer);

// HTTP请求函数
static char* http_get_json(const char* host, const char* path) {
    if (!host || !path) {
        return NULL;
    }
    
    struct hostent *ht = gethostbyname(host);
    if (!ht) {
        return NULL;
    }
    
    if (!ht->h_addr_list || !ht->h_addr_list[0]) {
        return NULL;
    }

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1) {
        return NULL;
    }

    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(80);
    memcpy(&addr.sin_addr, ht->h_addr_list[0], ht->h_length);

    if (connect(sockfd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
        close(sockfd);
        return NULL;
    }

    char request[1024];
    int req_len = snprintf(request, sizeof(request),
        "GET %s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n", path, host);
    if (req_len <= 0 || req_len >= sizeof(request)) {
        close(sockfd);
        return NULL;
    }

    if (send(sockfd, request, strlen(request), 0) <= 0) {
        close(sockfd);
        return NULL;
    }

    char *response = malloc(1024);
    if (!response) {
        close(sockfd);
        return NULL;
    }
    int total = 0;
    int buffer_size = 1024;
    int n;

    while ((n = recv(sockfd, response + total, buffer_size - total - 1, 0)) > 0) {
        total += n;
        if (total >= buffer_size - 100) {
            buffer_size *= 2;
            char *new_response = realloc(response, buffer_size);
            if (!new_response) {
                free(response);
                close(sockfd);
                return NULL;
            }
            response = new_response;
        }
    }

    if (n < 0) {
        free(response);
        close(sockfd);
        return NULL;
    }

    response[total] = '\0';
    close(sockfd);

    char *json_start = strstr(response, "{");
    char *json_end = strrchr(response, '}');
    if (!json_start || !json_end || json_start > json_end) {
        free(response);
        return NULL;
    }

    size_t json_len = json_end - json_start + 2;
    char *json = malloc(json_len);
    if (!json) {
        free(response);
        return NULL;
    }
    snprintf(json, json_len, "%s", json_start);
    
    free(response);
    return json;
}

// 提取城市名
static char* extract_city(const char* att) {
    if (!att) {
        return NULL;
    }
    
    char *last_comma = strrchr(att, ',');
    char *city = NULL;
    
    if (last_comma && *(last_comma + 1) != '\0') {
        city = strdup(last_comma + 1);
    } else {
        city = strdup(att);
    }
    
    return city;
}

// 获取IP对应的城市
static char* get_ip_city() {
    char *json = http_get_json("api.k780.com", 
        "/?app=ip.local&appkey=77066&sign=0199f3b81defea1da84e349798e66c89&format=json");
    if (!json) {
        return NULL;
    }

    cJSON *root = cJSON_Parse(json);
    if (!root) {
        free(json);
        return NULL;
    }

    cJSON *result = cJSON_GetObjectItem(root, "result");
    if (!result) {
        cJSON_Delete(root);
        free(json);
        return NULL;
    }

    cJSON *att = cJSON_GetObjectItem(result, "att");
    if (!att || !att->valuestring) {
        cJSON_Delete(root);
        free(json);
        return NULL;
    }

    char *city = extract_city(att->valuestring);

    cJSON_Delete(root);
    free(json);
    return city;
}

// 定义数据结构用于传递给UI更新函数
typedef struct {
    char *city;
    char *json;
} ui_update_data_t;

// UI更新回调函数
static void update_ui_callback(lv_timer_t *timer) {
    ui_update_data_t *data = (ui_update_data_t *)timer->user_data;
    
    if (!data || !data->city || !data->json) {
        lv_timer_del(timer);
        return;
    }

    // 更新地点
    if (placevalue) {
        lv_label_set_text(placevalue, data->city);
        lv_obj_invalidate(placevalue);
    }

    // 解析JSON并更新天气数据
    cJSON *root = cJSON_Parse(data->json);
    if (root) {
        cJSON *result = cJSON_GetObjectItem(root, "result");
        if (result) {
            cJSON *item;
            
            // 更新天气
            if ((item = cJSON_GetObjectItem(result, "weather")) && item->valuestring && weathervalue) {
                lv_label_set_text(weathervalue, item->valuestring);
                lv_obj_invalidate(weathervalue);
            }
            
            // 更新温度
            if ((item = cJSON_GetObjectItem(result, "temperature")) && item->valuestring && Tempvalue) {
                lv_label_set_text(Tempvalue, item->valuestring);
                lv_obj_invalidate(Tempvalue);
            }
            
            // 更新风向
            if ((item = cJSON_GetObjectItem(result, "wind")) && item->valuestring && windvalue) {
                lv_label_set_text(windvalue, item->valuestring);
                lv_obj_invalidate(windvalue);
            }
            
            // 更新湿度
            if ((item = cJSON_GetObjectItem(result, "humidity")) && item->valuestring && Humidityvalue) {
                lv_label_set_text(Humidityvalue, item->valuestring);
                lv_obj_invalidate(Humidityvalue);
            }
        }
        cJSON_Delete(root);
    }

    // 清理资源
    free(data->city);
    free(data->json);
    free(data);
    lv_timer_del(timer);
}

// 定时器回调函数
static void weather_timer_callback(lv_timer_t *timer) {
    weather_update_from_ip();
}

// 初始化天气模块
void weather_init(void) {
    // 等待UI完全初始化
    int retry = 0;
    while ((!ui_placevalue || !ui_weathervalue || !ui_Tempvalue || !ui_windvalue || !ui_Humidityvalue) && retry < 5) {
        sleep(1);
        retry++;
    }

    // 绑定UI元素
    placevalue = ui_placevalue;
    weathervalue = ui_weathervalue;
    Tempvalue = ui_Tempvalue;
    windvalue = ui_windvalue;
    Humidityvalue = ui_Humidityvalue;

    // 初始化测试显示
    if (placevalue) {
        lv_label_set_text(placevalue, "初始化中...");
        lv_obj_invalidate(placevalue);
    }
    if (weathervalue) {
        lv_label_set_text(weathervalue, "初始化中...");
        lv_obj_invalidate(weathervalue);
    }
    if (Tempvalue) {
        lv_label_set_text(Tempvalue, "初始化中...");
        lv_obj_invalidate(Tempvalue);
    }
    if (windvalue) {
        lv_label_set_text(windvalue, "初始化中...");
        lv_obj_invalidate(windvalue);
    }
    if (Humidityvalue) {
        lv_label_set_text(Humidityvalue, "初始化中...");
        lv_obj_invalidate(Humidityvalue);
    }
    
    // 强制刷新显示
    lv_refr_now(lv_disp_get_default());
    
    // 创建定时器，每5分钟更新一次
    if (!weather_timer) {
        weather_timer = lv_timer_create(weather_timer_callback, 300000, NULL);
        // 立即执行一次更新
        weather_timer_callback(NULL);
    }
}

// 更新指定城市天气
void weather_update_by_city(const char *city) {
    if (!city || strlen(city) == 0) {
        return;
    }

    // 先更新地点显示
    if (placevalue) {
        lv_label_set_text(placevalue, city);
        lv_obj_invalidate(placevalue);
    }

    // 构建天气请求路径
    char path[1024];
    snprintf(path, sizeof(path),
        "/?app=weather.today&cityNm=%s&appkey=77066&sign=0199f3b81defea1da84e349798e66c89&format=json", city);

    // 获取天气数据
    char *json = http_get_json("api.k780.com", path);
    if (!json) {
        return;
    }

    // 准备传递给UI更新函数的数据
    ui_update_data_t *data = malloc(sizeof(ui_update_data_t));
    if (!data) {
        free(json);
        return;
    }
    data->city = strdup(city);
    data->json = json;

    // 创建LVGL定时器在主线程更新UI
    lv_timer_t *timer = lv_timer_create(update_ui_callback, 0, data);

    // 强制刷新
    lv_refr_now(lv_disp_get_default());
}

// 从IP更新天气
void weather_update_from_ip(void) {
    char *city = get_ip_city();
    
    if (!city) {
        if (placevalue) {
            lv_label_set_text(placevalue, "未知位置");
            lv_obj_invalidate(placevalue);
            lv_refr_now(lv_disp_get_default());
        }
        return;
    }

    weather_update_by_city(city);
    free(city);
}

// 清理资源
void weather_cleanup(void) {
    if (weather_timer) {
        lv_timer_del(weather_timer);
        weather_timer = NULL;
    }
}
    